package edu.service.impl;

import edu.service.TeacherService;
import edu.vo.Teacher;
import edu.repository.TeacherRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class TeacherServiceImpl implements TeacherService {

    private final TeacherRepository teacherRepository;

    public TeacherServiceImpl(TeacherRepository teacherRepository) {
        this.teacherRepository = teacherRepository;
    }

    @Override
    public Teacher saveTeacher(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    @Override
    public Optional<Teacher> getTeacherById(Integer id) {
        return teacherRepository.findById(id);
    }

    @Override
    public List<Teacher> getAllTeachers() {
        return teacherRepository.findAll();
    }

    @Override
    public void deleteTeacherById(Integer id) {
        teacherRepository.deleteById(id);
    }

    @Override
    public Teacher updateTeacher(Integer id, Teacher teacher) {
        return teacherRepository.findById(id)
                .map(existingTeacher -> {
                    existingTeacher.setUserName(teacher.getUserName());
                    existingTeacher.setName(teacher.getName());
                    existingTeacher.setSex(teacher.getSex());
                    existingTeacher.setBirthday(teacher.getBirthday());
                    existingTeacher.setPhone(teacher.getPhone());
                    existingTeacher.setEducation(teacher.getEducation());
                    existingTeacher.setMotto(teacher.getMotto());
                    return teacherRepository.save(existingTeacher);
                })
                .orElse(null);
    }
}